package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.*;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.BaiduMapUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private BaiduMapUtil baiduMapUtil;
    /**
     * 用户下单
     */
    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1、判断地址是否为空,判断购物车是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (ObjectUtils.isEmpty(addressBook)){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //计算两地距离,如果大于5公里抛异常
        String dest = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        Integer distance = baiduMapUtil.getDistance("北京市朝阳区新街大道一号楼8层", "北京市", dest, addressBook.getCityName());
        if (distance > 5000){
            throw new OutDeliveryRangeException("超出配送范围,最大配送范围为5公里");
        }
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(userId).build();
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        if (ObjectUtils.isEmpty(list)){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //清空购物车
        shoppingCartMapper.cleanShoppingCart(shoppingCart);
        //封装Orders
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(userId);
        //订单号采用时间戳
        orders.setNumber(String.valueOf((Long)System.currentTimeMillis()));
        orders.setPayStatus(Orders.UN_PAID);
        orders.setUserName(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setOrderTime(LocalDateTime.now());
        orders.setConsignee(addressBook.getConsignee());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orderMapper.submitOrder(orders);
        List<OrderDetail> orderDetails = new ArrayList<>();
        list.forEach(s -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(s, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        });
        //向明细表插入n条数据
        orderMapper.insertBatch(orderDetails);
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 历史订单查询接口
     */
    @Override
    public PageResult queryByPage(OrdersPageQueryDTO pageQueryDTO,boolean isAdmin) {
        if (!isAdmin){
            pageQueryDTO.setUserId(BaseContext.getCurrentId());
        }
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        Page<OrderVO> p = orderMapper.queryByPage(pageQueryDTO);
        List<OrderVO> list = p.getResult();
        list.forEach(l -> {
            List<OrderDetail> orderDetailList = l.getOrderDetailList();
            StringBuilder sb = new StringBuilder();
            orderDetailList.forEach(o -> sb.append(o.getName() + "*" + o.getNumber() + ","));
            String s = sb.toString();
            s = s.substring(0,s.lastIndexOf(","));
            l.setOrderDishes(s);
        });
        PageResult pr = new PageResult();
        pr.setRecords(p.getResult());
        pr.setTotal(p.getTotal());
        return pr;
    }

    /**
     * 查询订单详情
     */
    @Override
    public OrderVO queryOrderDetail(Long id) {
        OrderVO orderVO = orderMapper.queryOrderDetail(id);
        return orderVO;
    }

    /**
     * 取消订单
     */
    @Override
    public void cancelOrder(Long id) {
        Orders o = Orders.builder().id(id).status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now()).build();
        orderMapper.cancelOrder(o);
    }
    /**
     * 再来一单
     */
    @Override
    public void repetitionOrder(Long id) {
        OrderVO orderVO = orderMapper.queryOrderDetail(id);
        List<OrderDetail> orderDetailList = orderVO.getOrderDetailList();
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        orderDetailList.forEach(o -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(o, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartList.add(shoppingCart);
        });
        shoppingCartMapper.addBatchShopping(shoppingCartList);
    }
    /**
     * 取消订单
     */
    @Override
    public void admincancelOrder(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = cancelOrReject(ordersCancelDTO.getId());
        BeanUtils.copyProperties(ordersCancelDTO, orders);
        orderMapper.cancelOrder(orders);
    }
    /**
     * 拒单
     */
    @Override
    public void adminrejectOrder(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = cancelOrReject(ordersRejectionDTO.getId());
        BeanUtils.copyProperties(ordersRejectionDTO, orders);
        orderMapper.cancelOrder(orders);
    }

    public Orders cancelOrReject(Long id){
        Orders orders = new Orders();
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);
        Orders o = orderMapper.getById(id);
        //判断是否已经支付，支付了需要退款
        if (o.getPayStatus() == Orders.PAID){
            orders.setPayStatus(Orders.REFUND);
            try {
                weChatPayUtil.refund(o.getNumber(),
                        String.valueOf(System.currentTimeMillis()),
                        o.getAmount(),o.getAmount());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return orders;
    }
    /**
     * 接单
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersConfirmDTO, orders);
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.cancelOrder(orders);
    }
    /**
     * 派送订单
     */
    @Override
    public void deliveryOrder(Long id) {
        Orders orders = Orders.builder().id(id).status(Orders.DELIVERY_IN_PROGRESS).build();
        orderMapper.cancelOrder(orders);
    }
    /**
     * 完成订单
     */
    @Override
    public void completeOrder(Long id) {
        Orders orders = Orders.builder().
                id(id).status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now()).build();
        orderMapper.cancelOrder(orders);
    }

    /**
     * 各个状态的订单数量统计
     */
    @Override
    public OrderStatisticsVO countOrderByStatus() {
        OrderStatisticsVO orderStatisticsVO = orderMapper.countOrderByStatus();
        return orderStatisticsVO;
    }
}
